package com.example.forum.interceptor;

import com.example.forum.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Created with IntelliJ IDEA.
 * Description: 登录拦截器
 * User: DELL
 * Date: 2023-09-21
 * Time: 17:13
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${bit-forum.login.url}")
    private String defaultUrl;

    /**
     * 访问需要登录的页面时的预处理
     *
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 尝试获取 session
        HttpSession session = request.getSession(false);
        // 验证 session
        if (session != null && session.getAttribute(AppConfig.USER_SESSION_KEY) != null) {
            return true;
        }
        // 检验配置文件中的 URL 不是以 '/' 开头的,若不是则加上
        if (!defaultUrl.startsWith("/")) {
            defaultUrl = "/" + defaultUrl;
        }
        // 重定向到登录页面
        response.sendRedirect(defaultUrl);
        // 打印日志
        log.warn("检测到未登录状态下访问,URL = " + request.getRequestURL());
        return false;
    }
}
